<?php

/*
  +--------------------------------------------------------------------------
  |   Web: http://www.enbac.com
  |   Started date : 30/06/2008
  +---------------------------------------------------------------------------
  |   > Script written by Nova
  +---------------------------------------------------------------------------
 */

if (eregi(basename(__FILE__), $_SERVER['PHP_SELF'])) {
    print "<h1>Incorrect access</h1>You cannot access this file directly.";
    exit();
}

class ajax_shop {

    function playme() {
        $code = AZLib::getParam('code');
        switch ($code) {
            case 'set_label':
                $this->set_label();
                break;
            case 'list_user_comments':
                $this->list_user_comments();
                break;
            case 'list_view':
                $this->list_view();
                break;
            case 'feedback':
                $this->fn_comment();
                break;
            case 'del_comment':
                $this->fn_del_comment();
                break;
            case 'get_more_comment':
                $this->get_more_comment();
                break;
            case 'mark_label':
                $this->mark_label();
                break;
            case 'load_shop_label':
                $this->load_shop_label();
                break;
            default:
                $this->home();
                break;
        }
    }

    function home() {
        global $display;
        die("Nothing to do...");
    }

    function set_label() {
        $user_id = (int) Url::get('user_id', 0);
        $item_id = (int) Url::get('item_id', 0);
        $label_id = (int) Url::get('label_id', 0);
        $current_label_id = (int) Url::get('current_label_id', 0);

        if (!$user_id && !$item_id && !User::is_login() && $user_id != User::id() && !User::have_permit(ADMIN_ITEM)) {
            echo "no_perm";
            exit();
        }

        $item = Item::get_item($item_id);

        $label = DB::select('label', 'id=' . $label_id . ' AND user_id=' . $user_id);
        $user = User::getUser($user_id);
        if ($item && $user && $item['status'] == 1 && $item['user_id'] == $user_id) {
            if ($label_id && $label) {
                if ($label['parent_id']) {//Kéo vào nhãn con
                    if ($current_label_id == $label_id) {//Nếu kéo thả vào chính nhãn nó đang có
                        echo "success";
                        exit();
                    }

                    DB::query('DELETE FROM label_item WHERE label_id=' . $label['parent_id'] . ' AND item_id=' . $item_id . " AND user_id=" . $user_id);

                    $label_item = array(
                        'label_id' => $label_id,
                        'label_top_id' => ($label['parent_id'] ? $label['parent_id'] : $label_id),
                        'item_id' => $item_id,
                        'user_id' => $user_id,
                        'user_name' => $user['user_name'],
                    );
                    DB::insert('label_item', $label_item);
                    echo "success";
                    exit();
                } else {//Kéo vào nhãn cha
                    if ($current_label_id) {
                        if ($current_label_id != $label_id) {//Đang ở nhãn con kéo thả vào nhãn cha, hoặc kéo thả vào nhãn cha khác
                            //Nếu đã có nhãn con khác cùng nhãn cha này!
                            if (DB::select('label_item', 'label_top_id=' . $label_id . ' AND label_id!=' . $current_label_id . ' AND item_id=' . $item_id . " AND user_id=" . $user_id)) {//Nếu đã có nhãn con nào thuộc nhãn cha này
                                DB::query('DELETE FROM label_item WHERE label_id=' . $current_label_id . ' AND item_id=' . $item_id . " AND user_id=" . $user_id);
                                if ($current_label_id) {
                                    echo "del_success";
                                    exit();
                                }
                            } else {
                                DB::update('label_item', array(
                                            'label_id' => $label_id,
                                            'label_top_id' => $label_id,
                                                ), 'label_id=' . $current_label_id . ' AND item_id=' . $item_id . " AND user_id=" . $user_id);
                            }

                            echo "success";
                            exit();
                        }
                        //Kéo vào chính nhãn cha
                        elseif (DB::select('label_item', 'label_top_id=' . $label_id . ' AND label_id!=' . $current_label_id . ' AND item_id=' . $item_id . " AND user_id=" . $user_id)) {//Nếu đã có nhãn con nào thuộc nhãn cha này
                            DB::query('DELETE FROM label_item WHERE label_id=' . $current_label_id . ' AND item_id=' . $item_id . " AND user_id=" . $user_id);
                            echo "del_success";
                            exit();
                        } else {//Nếu ko có nhãn con nào thuộc nhãn cha này
                            DB::update('label_item', array(
                                        'label_id' => $label_id,
                                        'label_top_id' => $label_id,
                                            ), 'label_id=' . $current_label_id . ' AND item_id=' . $item_id . " AND user_id=" . $user_id);
                        }
                        echo "success";
                        exit();
                    } elseif (!DB::select('label_item', '(label_id=' . $label_id . ' OR label_top_id=' . $label_id . ') AND item_id=' . $item_id . " AND user_id=" . $user_id)) {
                        $label_item = array(
                            'label_id' => $label_id,
                            'label_top_id' => ($label['parent_id'] ? $label['parent_id'] : $label_id),
                            'item_id' => $item_id,
                            'user_id' => $user_id,
                            'user_name' => $user['user_name'],
                        );
                        DB::insert('label_item', $label_item);
                        echo "success";
                        exit();
                    }
                    //DB::query('DELETE FROM label_item WHERE label_top_id='.$label_id.' AND item_id='.$item_id." AND user_id=".$user_id);
                }
            } else {//remove
                DB::delete('label_item', 'item_id=' . $item_id . ' AND user_id=' . $user_id);
                echo "del_success";
                exit();
            }
        } else {
            echo "no_exist";
            exit();
        }
    }

    function list_user_comments() {
        global $display;

        require_once(DIR_MODULE . "Shop/forms/UserComment.php");
        $UserCommentForm = new UserCommentForm("UserCommentForm");
        $UserCommentForm->draw();
        System::halt();
    }

    function list_view() {
        global $display;
        $this->load_shop_label();
        System::halt();
    }

    function fn_comment() {
        header("Content-type: application/xml");

        $content = trim(AZLib::getParam('content'));
        $comment_id = (int) Url::get('comment_id', 0);
        $comment_row = array();


        if ($content == '') {
            echo "<comments><content>no_perm</content></comments>";
            exit();
        }
        if (User::is_login()) {
            if (User::is_block()) {
                echo "<comments><content>no_perm</content></comments>";
                exit();
            }

            $sender_user_name = User::user_name();
            $sender_email = '';
        } else {
            $sender_user_name = AZLib::getParam('user_name');
            $sender_email = AZLib::getParam('sender_email', '');

            $username_lower = strtolower($sender_user_name);
            if (strlen($username_lower) < 3 || $username_lower == 'admin' || $username_lower == 'administrator' || $username_lower == 'moderator' || $username_lower == 'enbac') {
                echo "<comments><content>bad_word</content></comments>";
                exit();
            }
        }

        if ($comment_id) {
            $comment_row = DB::select("user_entry_comment", "id=$comment_id");

            if (!$comment_row || ($comment_row && User::is_login() && $comment_row['sender_user_id'] == User::id())) {//Không được trả lời cho chính mình!
                echo "<comments><content>no_perm</content></comments>";
                exit();
            }

            $entry_id = $comment_row['entry_id'];
        } else {
            $entry_id = (int) Url::get('entry_id', 0);
        }

        if (!$entry_id || !$user_entry = DB::select('user_entry', "id=$entry_id")) {
            echo "<comments><content>no_perm</content></comments>";
            exit();
        }

        if (User::is_login() && AZLib::isBlackList(User::id(), $user_entry['user_id'])) {
            echo "<comments><content>blacklist</content></comments>";
            exit();
        }

        if ((!User::is_login() && AZLib::checkBadWord($sender_user_name)) || AZLib::checkBadWord($content)) {
            echo "<comments><content>bad_word</content></comments>";
            exit();
        }
        if (AZLib::checkBadWord($content)) {
            echo "<comments><content>bad_word</content></comments>";
            exit();
        }

        if (!User::is_login()) {
            $captcha = AZLib::getParam('captcha');
            if (!isset($_SESSION["enbac_validate"]) || $captcha == '' || $captcha != $_SESSION["enbac_validate"]) {
                echo "<comments><content>false_captcha</content></comments>";
                exit();
            }
        }

        $content = preg_replace("/\n/", "<br />", $content);
        $content = str_replace('<br /><br />', '&nbsp;', $content);

        if ($comment_row) {
            if ($comment_row['parent_id']) {
                $parent_id = $comment_row['parent_id'];
                //$sender_user_name 	= $comment_row['sender_user_name'];
                $sender_user_name = User::user_name();

                if ($comment_row['sender_user_id'])
                    $content = '@<a href="' . WEB_DIR . $comment_row['sender_user_name'] . '" class="fast_reply_link" title="' . $sender_user_name . '">' . $comment_row['sender_user_name'] . '</a>: ' . $content;
                else
                    $content = '<font color="#999">@<span style="text-decoration:underline">' . $sender_user_name . '</span> </font>: ' . $content;
            }
            else {
                $parent_id = $comment_row['id'];
            }
        } else {
            $parent_id = 0;
        }

        // set guest cookie
        if (!User::id()) {
            $week = 60 * 60 * 24 * 365 + TIME_NOW;
            AZLib::my_setcookie("guest_name", $sender_user_name, $week);
            AZLib::my_setcookie("guest_email", $sender_email, $week);
        }

        $user_entry_comment = array(
            'content' => $content,
            'entry_id' => $user_entry['id'],
            'time' => TIME_NOW,
            'order_time' => TIME_NOW,
            'post_ip' => AZLib::ip(),
            'parent_id' => $parent_id,
            'receiver_user_id' => $user_entry['user_id'],
            'display' => 1,
            'receiver_user_name' => $user_entry['user_name']
        );

        if (User::id()) {
            $user_entry_comment['sender_user_id'] = User::id();
        } else {
            $user_entry_comment['sender_user_id'] = 0;
            $user_entry_comment['sender_email'] = $sender_email;
        }

        $user_entry_comment['sender_user_name'] = $sender_user_name;

        if ($comment_row && $comment_row['sender_user_id'] && $comment_row['sender_user_id'] != $user_entry['user_id']) {//Lưu lại người được trả lời
            $user_entry_comment['replied_user_id'] = $comment_row['sender_user_id'];
            $user_entry_comment['replied_user_name'] = $comment_row['sender_user_name'];
        } elseif ($comment_row && $comment_row['sender_user_id'] == $user_entry['user_id']) {
            $user_entry_comment['replied_status'] = 1;
        }

        $id = DB::insert('user_entry_comment', $user_entry_comment);

        if ($id) {
            if (!User::id()) {
                AZLib::reload_captcha();
            }

            if ($parent_id) {
                $re = DB::query("SELECT id FROM user_entry_comment WHERE parent_id = $parent_id AND display = 1 ORDER BY id DESC LIMIT 3,1");

                if ($re) {
                    if ($row = mysql_fetch_assoc($re)) {
                        if ($row) {
                            DB::query("UPDATE user_entry_comment SET display = 0 WHERE parent_id = $comment_id AND display = 1 AND id<={$row['id']}");
                        }
                    }
                }

                if ($comment_id == $parent_id) {
                    if (User::is_login() && $user_entry['user_id'] == User::id())
                        DB::query("UPDATE user_entry_comment SET have_child = have_child + 1, order_time = " . time() . ", status=1 WHERE id = $parent_id");
                    else
                        DB::query("UPDATE user_entry_comment SET have_child = have_child + 1, order_time = " . time() . " WHERE id = $parent_id");
                }
                else {
                    DB::query("UPDATE user_entry_comment SET have_child = have_child + 1, order_time = " . time() . " WHERE id = $parent_id");
                    if (User::is_login() && $user_entry['user_id'] == User::id()) {
                        DB::query("UPDATE user_entry_comment SET status=1 WHERE id = $comment_id");
                    }
                }

                //Cập nhật đã đọc - trả lời cho feed
                DB::query("UPDATE feed SET status = 1 WHERE ref_id = $comment_id AND type=5");

                //Cập nhật lại replied_status nếu chưa được check!
                if (User::is_login() && $comment_row['replied_user_id'] == User::id() && $comment_row['replied_status'] == 0) {
                    DB::query("UPDATE user_entry_comment SET replied_status=1 WHERE id = $comment_id");
                    //Cập nhật đã đọc - trả lời cho feed
                    DB::query("UPDATE feed SET status = 1 WHERE ref_id = $comment_id AND type=6");
                }
            }
        }

        $total_feedback = DB::count('user_entry_comment', 'entry_id="' . $user_entry['id'] . '"');
        DB::update_id('user_entry', array('reply_count' => $total_feedback), $user_entry['id']);

        $xml = "<comments><content><![CDATA[" . AZLib::parseBBCode($content) . "]]></content><post_time>vài giây trước</post_time>";

        $xml.= "<id>" . ($id % 3) . "</id><parent_id>$parent_id</parent_id></comments>";

        echo $xml;

        $user_item = User::getUser($user_entry['user_id']);

        if ($user_item && $user_item['email'] && $user_item['email_alert'] && $user_item['id'] != User::id()) {
            if (User::id())
                $sender_email = '';

            $link = WEB_ROOT . '?page=user_entry&user_name=' . $user_entry['user_name'] . '&cmd_entry=view&entry_id=' . $user_entry['id'] . '&ebname=' . AZLib::safe_title($user_entry['title']);
            $link = AZRewrite::formatUrl($link);
            $title = "<a href='$link' target='_blank' style='text-decoration:none;color:#003399;'><font color='#003399'>{$user_entry['title']}</font></a>";

            AZLib::addCronJob('entry_comment', AZLib::parseBBCode($content, true), $user_item['id'], User::id() ? User::user_name() : $sender_user_name, $sender_email, $user_entry['id'], $title, $link);
        }

        System::halt();
    }

    function fn_del_comment() {
        $id = (int) Url::get('id', 0);
        $sql = "SELECT id,entry_id,sender_user_id,display,receiver_user_id,have_child,parent_id from user_entry_comment WHERE id=" . $id;
        $comment = DB::fetch($sql);

        if (User::is_block()) {
            echo "not_perm";
            exit();
        }

        if (User::have_permit(ADMIN_ITEM) || (User::id() == $comment['receiver_user_id'] && $comment['sender_user_id'] == 0)) {
            if (DB::delete('user_entry_comment', 'id=' . $id)) {
                DB::query("DELETE FROM feed WHERE ref_id = $id AND type IN(5,6)");

                if ($comment['have_child'] > 0) {
                    DB::delete('comment', 'parent_id=' . $id);
                }

                if ($comment['entry_id'] > 0) {
                    if ($comment['parent_id'] > 0) {
                        DB::query('UPDATE 	user_entry_comment
								   SET 		have_child = have_child-1
								   WHERE 	id=' . $comment['parent_id'] . ' ');
                        if ($comment['display'] == 1) {
                            DB::query('UPDATE user_entry_comment SET display = 1 where entry_id = ' . $comment['entry_id'] . ' AND parent_id = ' . $comment['parent_id'] . ' AND display = 0 order by id DESC limit 1');
                        }
                    }

                    $value = 'reply_count=reply_count-' . (1 + $comment['have_child']);
                    DB::query('UPDATE 	user_entry
								   SET 		' . $value . '
								   WHERE 	id="' . $comment['entry_id'] . '" ');
                }
                echo $id;
                exit();
            } else {

                echo "unsuccess";
                exit();
            }
        }
    }

    function get_more_comment() {
        $parent_id = AZLib::getParam('comment_id');
        $item_user_name = AZLib::getParam('item_user_name');
        $entry_id = AZLib::getParam('entry_id');
        //$cat_id  	= AZLib::getParam('cat_id');
        $guest_email = AZLib::getParam('guest_email');
        $guest_name = AZLib::getParam('guest_name');

        $cur_id = AZLib::getParam('cur_id', 0);
        $item_user_id = AZLib::getParam('user_id');

        $show_guest_email = (User::have_permit(ADMIN_ITEM) || User::id() == $item_user_id);

        $sql = 'SELECT `user_entry_comment`.`id`, `time`, `content`, `entry_id`, `sender_email`, `sender_user_name`, `receiver_user_name`,`sender_user_id`, `receiver_user_id`, `parent_id`, `have_child`, user.avatar_url, user.id as user_id, user.gids, user.block_time, user.img_server FROM `user_entry_comment` LEFT JOIN `user` ON user.id=user_entry_comment.sender_user_id
					WHERE `user_entry_comment`.`parent_id` =' . $parent_id . ' AND `user_entry_comment`.`display`=0 ORDER BY time DESC LIMIT 0,100';
        $re = DB::query($sql);

        $i = 0;
        $result = '';
        $str_user_id = '';
        while ($item = mysql_fetch_assoc($re)) {
            $item['index'] = $i;
            $i++;

            if ($item['block_time'] > TIME_NOW) {
                $item['is_block'] = 1;
            } else {
                $item['is_block'] = 0;
            }

            $str_user_id .= ( $str_user_id != '' ? ',' : '') . $item['sender_user_id'];

            //set quyen quan tri
            if ($item['gids']) {
                $is_admin_mod = CGlobal::$group[User::check_admin($item['gids'])];
            } else {
                $is_admin_mod = array();
            }
            $item['is_admin_mod'] = $is_admin_mod;
            if ((TIME_NOW - $item['time']) < (24 * 3600)) {
                $time_left = TIME_NOW - $item['time'];
                $hour = floor($time_left / 3600);
                $day = '';

                $minute = floor(($time_left % 3600) / 60) . ' phút';
                $time_left = ($hour ? $hour . ' giờ ' : '') . $minute;

                if ($time_left == 0) {
                    $time_left = 'Vài giây';
                }

                $item['created_time'] = $time_left . ' trước';
            } elseif (date('Y') != date('Y', $item['time']))
                $item['created_time'] = date('H:i | d.m.Y', $item['time']);
            else
                $item['created_time'] = date('H:i | d.m', $item['time']);

            $item['content'] = AZLib::parseBBCode($item['content']);

            if ($item['sender_user_id']) {
                $item['sender_link'] = Url::build('shop', array('user_name' => $item['sender_user_name']));
            } else {
                $item['sender_link'] = '';
            }

            if (User::have_permit(ADMIN_ITEM)) {
                $item['del_link'] = Url::build_current(array('cmd' => 'del_comment', 'id' => $item['entry_id'], 'cid' => $item['id']));
            } else {
                $item['del_link'] = '';
            }

            $item['URL_badcontent'] = Url::build('item_detail', array('id' => Url::get('id'), 'ctype' => 'comment', 'id_comment' => $item['id']));

            $result .= '<tr id="' . $item['id'] . '"';

            if ($item['user_id'] != $cur_id && $item['sender_user_id'] != 0) {
                $result .= ' onmouseover="show_hide_menu(' . $item['id'] . ')" onmouseout="show_hide_menu(' . $item['id'] . ')" ';
            }
            $result .= '><td width="28" align="right" valign="top"><div style="height:5px"><span></span></div>';

            if ($item['sender_user_id'] == 0) {
                if ($item['id'] % 3 == 0) {
                    $item['sender_avatar_url'] = 'style/images/avatar_01.gif';
                } elseif ($item['id'] % 3 == 1) {
                    $item['sender_avatar_url'] = 'style/images/avatar_02.gif';
                } else {
                    $item['sender_avatar_url'] = 'style/images/avatar_03.gif';
                }
                $html_content = '';
                $result .= '<div class="feedbackAvatarSub" id="avatar_content_' . $item['user_id'] . '"><img src="' . $item['sender_avatar_url'] . '" width="25" height="25" /></div>';
            } else {

                if ($item['avatar_url']) {
                    $item['sender_avatar_url'] = AZLib::getImageThumb($item['avatar_url'], 60, 0, 1, $item['img_server']);
                    if ($item['parent_id'] > 0) {
                        $html_content = '<a href="' . $item['sender_link'] . '"><img src="' . $item['sender_avatar_url'] . '" width="25"/></a>';
                    } else {
                        $html_content = '<a href="' . $item['sender_link'] . '"><img src="' . $item['sender_avatar_url'] . '" width="50"/></a>';
                    }
                } else {
                    $item['sender_avatar_url'] = '';
                    if ($item['parent_id'] > 0) {
                        $html_content = '<a href="' . $item['sender_link'] . '"><img src="style/images/50x50.gif" width="25" height="25" /></a>';
                    } else {
                        $html_content = '<a href="' . $item['sender_link'] . '"><img src="style/images/50x50.gif" width="50" height="50" /></a>';
                    }
                }

                $result .= '<div class="profile_load"  id="u' . $item['user_id'] . '"><div class="feedbackAvatarSub" ';
                $result .= ' id="avatar_content_' . $item['user_id'] . '"><div class="bubbleInfo"><div class="commentAva trigger">' . $html_content . '</div><!-- BEGIN POPUP MENU --><div class="popup" style="text-align: left;"><div class="show_mini_profile_u' . $item['user_id'] . '" style="display:none;"><div class="show_mini_profile_' . $item['user_id'] . '"></div></div><div class="hide_mini_profile_u' . $item['user_id'] . '"><div class="contentPop" style="background-color:#fff"><div style="margin:4px;"><div class="blastTopLeft"><div class="blastTopRight"><div class="blastTopbg"><span></span></div></div></div><div class="blast"><img src="style/images/ajax-loader4.gif" width="62" height="13" /></div><div class="blastBottomLeft"><div class="blastBottomRight"><div class="blastBottombg"><span></span></div></div></div></div></div></div></div><!--END POPUP MENU --></div></div></div>';
            }
            $result .= '</td><td valign="top"><div class="contentFeedback" align="left"><div ';
            if (isset($item['is_admin_mod']['id']) && ($item['is_admin_mod']['id'] == 9 || $item['is_admin_mod']['id'] == 1))
                $result .= ' class="topFeedback_admin" ';
            elseif (isset($item['is_admin_mod']['id']) && ($item['is_admin_mod']['id'] == 2 || $item['is_admin_mod']['id'] == 3))
                $result .= ' class="topFeedback_mod" ';
            elseif ($item['sender_user_name'] == $item_user_name)
                $result .= ' class="topFeedbackSelf" ';
            else
                $result .= ' class="topFeedback"';

            $result .= ' >';

            if ($item['sender_user_id'] == 0) {
                $result .= ' <span class="guest_name">' . $item['sender_user_name'];
                $result .= ( $show_guest_email) ? '<a href="mailto:' . $item['sender_email'] . '" title="Gửi e-mail cho người dùng này!"><img src="style/images/comment_email/email.gif" border="0" width="15" height="11"/></a>' : '';
                $result .= '</span>';
            } else {
                $result .= ' <a ';
                $result .= ( $item['is_block'] == 1) ? ' title="Đang bị khóa nick" ' : ' ';
                $result .= ( $item['is_admin_mod']) ? ' title="' . $item['is_admin_mod']['des'] . '" ' : ' ';
                $result .= '  href="' . WEB_DIR . $item['sender_user_name'] . '">';
                $result .= ( $item['is_block'] == 1) ? ' <s><i> ' : ' ';
                $result .= $item['sender_user_name'];
                $result .= ( $item['is_block'] == 1) ? ' </i></s> ' : ' ';
                $result .= '</a>';
            }
            $result .= ' <span class="fb_time">' . $item['created_time'] . '</span> ';
            $result .= '<div class="floatRight" style=" height:16px"><div id="show_menu_' . $item['id'] . '" style="display:none">';

            if ($item['user_id'] != $cur_id && $item['sender_user_id'] != 0) {
                $result .= ' <span class="send_pm_fb" onclick="fn_send_pm_fb(' . $item['user_id'] . ',\'' . $item['sender_user_name'] . '\');" id="' . $item['user_id'] . '-' . $item['sender_user_name'] . '" style="margin-left:5px"><a href="javascript: void(0)"> Nhắn tin </a></span>|<span class="send_fb"><a href="' . WEB_DIR . AZRewrite::formatUrl('?page=shop&user_name=' . $item['sender_user_name'] . '&mode=comment') . '"> Lưu bút</a></span> ';
                if (($item != 1 && $item['sender_user_id'] == 0 && $cur_id == $item['receiver_user_id']) || $item['del_link']) {
                    $result .= ' | ';
                }
            }
            if (($item != 1 && $item['sender_user_id'] == 0 && $cur_id == $item['receiver_user_id']) || $item['del_link']) {
                $result .= '<span class="del_comment_aj" onmouseover="this.className=\'del_comment_aj_hover\'" onmouseout="this.className=\'del_comment_aj\'" onclick="fn_click_del_comment_aj(' . $item['id'] . ',' . $entry_id . ')" id="' . $item['id'] . '|' . $entry_id . '">Xoá</span>';
            }
            $result .='</div></div><div style="clear:both"><span></span></div>';


            $result .= ' </div><div class="detailFeedback" align="left"  style="width:485px; overflow:hidden">' . $item['content'] . '</div> ';

            if ($item['user_id'] != $cur_id) {
                $result .= ' <div id="reply_' . $item['id'] . '" class="btn_fast_reply" onmouseout="if(this.className==\'btn_fast_reply_hover\')this.className=\'btn_fast_reply\'" onmouseover="if(this.className==\'btn_fast_reply\')this.className=\'btn_fast_reply_hover\'" style="float:right"><a href="javascript:void(0);" onclick="show_box_reply(' . $item['id'] . ',' . $item['parent_id'] . ',\'' . $guest_name . '\',\'' . $guest_email . '\',\'' . $item['sender_user_name'] . '\',' . $item['sender_user_id'] . '); return true;"><img src="style/images/spacer.gif" width="48" height="17" /></a></div><div style="clear:right" id="box_reply_' . $item['id'] . '"></div>';
            }
            $result .= '</div></td></tr><tr id="space_' . $item['id'] . '"><td height="1" colspan="2"><div style="height:1px; margin:5px 0; background-color:#fff"><span></span></div></td></tr>';
            $result .= '</tr>';
        }

        echo($result);
        System::halt();
    }

    function mark_label() {
        $user_id = (int) Url::get('user_id');
        $item_id = (int) Url::get('item_id');
        $check_ids = Url::get('check_ids');
        $uncheck_ids = Url::get('uncheck_ids');

        if (!User::is_login() || !$user_id) {
            echo "not_login";
            exit;
        }
        if (!$item_id || !$user_id || (!User::is_admin() && (User::is_block() || User::id() != $user_id))) {
            echo "not_permit";
            exit;
        }

        $user = User::getUser($user_id);
        $item = Item::get_item($item_id);
        if (!$user || !$item || ($item && $item['user_id'] != $user_id)) {
            echo "not_permit";
            exit;
        }

        if ($uncheck_ids != '') {
            DB::delete("label_item", "user_id=$user_id AND label_id IN($uncheck_ids) AND item_id = $item_id");
        }

        if ($check_ids != '') {
            $label_id_arr = explode(',', $check_ids);
            $label_id_arr = $label_id_arr ? array_unique($label_id_arr) : $label_id_arr;

            if ($label_id_arr) {
                $insert_sql = '';

                foreach ($label_id_arr as $label_id) {
                    $insert_sql.= ( $insert_sql != '' ? ',' : '') . "($label_id,$item_id,$user_id,'{$user['user_name']}')";
                }

                if ($insert_sql != '') {
                    $insert_sql = "REPLACE INTO label_item (label_id, item_id, user_id, user_name) VALUES $insert_sql";
                    DB::query($insert_sql);
                }
            }
        }

        echo "success";
        exit;
    }

    function load_shop_label() {

        if (!CGlobal::$user_profile) {
            User::check_get_user();
        }

        if (CGlobal::$user_profile) {
            $mode_default = 'comment';

            if (!CGlobal::$shop_setting) {
                if (CGlobal::$user_profile['shop_setting']) {
                    CGlobal::$shop_setting = unserialize(stripslashes(CGlobal::$user_profile['shop_setting']));
                }

                if (!CGlobal::$shop_setting) {
                    CGlobal::$shop_setting = array(
                        'shop_name' => (CGlobal::$user_profile['full_name']) ? CGlobal::$user_profile['full_name'] : CGlobal::$user_profile['user_name'],
                        'default_mode' => 1,
                        'default_layout' => 1,
                        'item_list_mode' => 0,
                        'adv_banner' => '',
                    );
                }
            }

            if (CGlobal::$shop_setting && !isset(CGlobal::$shop_setting['default_layout'])) {
                CGlobal::$shop_setting['default_layout'] = 1;
            }

            if (Url::get("mode") == "comment" || CGlobal::$shop_setting['default_mode'] == 2) {
                CGlobal::$website_title = 'Lưu bút - Shop ' . CGlobal::$user_profile['user_name'];
            }

            if (!CGlobal::$shop_setting['default_mode']) {
                if (Url::get('mode') == 'shop' || DB::select('item', 'user_id=' . CGlobal::$user_profile['id'] . ' AND status=1')) {//Nếu có sp, mặc định là vào shop
                    CGlobal::$shop_setting['default_mode'] = 1;
                    $mode_default = 'shop';
                } else {//Nếu ko có sản phẩm, mặc định vào lưu bút
                    CGlobal::$shop_setting['default_mode'] = 2;

                    $mode_default = 'comment';
                }
            } else {
                if (CGlobal::$shop_setting['default_mode'] == 1) {
                    $mode_default = 'shop';
                } else {
                    $mode_default = 'comment';
                }
            }
        }

        if (CGlobal::$shop_label) {
            CGlobal::$website_title.=' | ' . CGlobal::$shop_label['name'];
            $this->label_id = CGlobal::$shop_label['id'];
        } else {
            $this->label_id = (int) Url::get('label_id', 0);
            if ($this->label_id) {
                CGlobal::$shop_label = DB::select("label", "id=" . $this->label_id);
            }
            if (!CGlobal::$shop_label) {
                $this->label_id = 0;
            }
        }

        $page_shop_item = (int) Url::get('page_shop_item', 1);
        $label_id = (int) Url::get("label_id", 0);
        $list_type = (int) Url::get("list_type", 0);

        global $display;

        $display->add('top_level_id', $label_id);
        $display->add('list_type', $list_type);

        $display->add('can_edit', (User::have_permit(ADMIN_ITEM) || User::id() == CGlobal::$user_profile['id']));

        $status_check = (User::id() == CGlobal::$user_profile['id'] || User::have_permit(ADMIN_ITEM)) ? ' status IN(0,1,2,3,4,5)' : ' status =1';

        if ($label_id) {
            $total_item = DB::fetch('SELECT count(*) AS total_row FROM label_item AS L JOIN item AS I ON L.item_id=I.id AND I.' . $status_check . ' AND I.user_id=' . CGlobal::$user_profile['id'] . ' WHERE L.user_id=' . CGlobal::$user_profile['id'] . ' AND L.label_id=' . $label_id, 'total_row', 0);
        } else {
            $total_item = DB::fetch('SELECT count(*) AS total_row FROM item WHERE ' . $status_check . ' AND user_id=' . CGlobal::$user_profile['id'], 'total_row', 0);
        }
        $pagging = '';
        $items = array();

        $divID = 'shop_item';
        $item_per_page = 0;

        if ($total_item) {
            $item_per_page = 9;
            $limit = '';
            $url_path = WEB_DIR . 'ajax.php?act=shop&code=load_shop_label&user_id=' . CGlobal::$user_profile['id'] . '&label_id=' . $label_id . ((!$list_type) ? '' : '&list_type=' . $list_type);
            
            $pagging = AZPagging::AjaxPaging($limit, $total_item, $item_per_page, 5, 'page_shop_item', '', false, false, $url_path, $divID, true);

            if ($label_id) {
                $display->add('label_name', CGlobal::$shop_label['name']);

                $select = 'SELECT I.id, I.name,I.sapo, I.user_name, I.user_id,I.description,I.category_id, I.read_count, I.reply_count, I.currency_id, I.price, I.province_id, I.up_time,I.price_out, I.brief, I.img_url, I.status, I.state, I.img_server
				FROM label_item AS L JOIN item AS I ON L.item_id=I.id AND I.' . $status_check . ' AND I.user_id=' . CGlobal::$user_profile['id'] . ' WHERE L.user_id=' . CGlobal::$user_profile['id'] . ' AND L.label_id=' . $label_id . ' ORDER BY shop_order, up_time DESC' . $limit;
            } else {
                $select = 'SELECT id, name, sapo, user_name, user_id, description, category_id, read_count, reply_count, currency_id, price, brief, img_url, province_id, up_time, price_out, status, state, img_server,sticky FROM item WHERE ' . $status_check . ' AND user_id=' . CGlobal::$user_profile['id'] . ' ORDER BY shop_order, up_time DESC' . $limit;
            }
            $re = DB::query($select);
            if (User::is_login()) {
                $wids = User::get_wishlist('wish_list_items');

                $w_items = array();
                if ($wids) {
                    $w_items = explode(',', $wids);
                }
            }
            if ($re) {
                AZLib::getProvinces();
                AZLib::getCats();

                $item_ids = '';
                while ($item = mysql_fetch_assoc($re)) {

                    $item['price'] = AZLib::convertCurrency($item['price'], $item['currency_id']);
                    $item['price_out'] = AZLib::convertCurrency($item['price_out'], $item['currency_id']);
                    $item['currency_id'] = 1;

                    if ($item['img_url']) {
                        $item['image_url'] = AZLib::getImageThumb($item['img_url'], 200, 200, 0, $item['img_server']);
                    }

                    if (isset(CGlobal::$allCategories[$item['category_id']])) {
                        $item['href'] = WEB_DIR . AZRewrite::formatUrl('?page=item_detail&id=' . $item['id'] . '&ebname=' . AZLib::safe_title(AZLib::word_limit($item['name'], 12, '')) . '&nice_name=' . CGlobal::$allCategories[$item['category_id']]['nice_name']);
                    } else {
                        $item['href'] = WEB_DIR . AZRewrite::formatUrl('?page=item_detail&id=' . $item['id'] . '&ebname=' . AZLib::safe_title(AZLib::word_limit($item['name'], 12, '')));
                    }

                    $tooltip = '';

                    $tooltip.= 'Xem: ' . $item['read_count'] . ' - Phản hồi: ' . $item['reply_count'];
                    $item['time_label'] = '';
                    $up_time = date('H:i | ', $item['up_time']);
                    if (date('d.m.y', $item['up_time']) == date('d.m.y', TIME_NOW)) {
                        $up_time.= '<font color="green">H&#244;m nay</font>';
                    } else {
                        $up_time.= date('d.m.y', $item['up_time']);
                    }
                    //$item['created_time'] = 'đăng '.AZLib::duration_time($item['up_time']);
                    $item['created_time'] = $up_time;

                    if ($item['price']) {
                        $item['price'] = number_format($item['price'], 0, ',', '.');
                        $item['currency_id'] = CGlobal::$currency[$item['currency_id']];
                    } else {
                        $item['price'] = '';
                        $item['currency_id'] = '';
                    }
                    $item['price_title'] = 'Giá bán';

                    if ($item['price_out'] > 0) {
                        $item['price_out'] = number_format($item['price_out'], 0, ',', '.') . ($item['currency_id'] == ' ' ? ' ' . CGlobal::$currency[$item['currency_id']] : '');
                    } else {
                        $item['price_out'] = '0';
                    }

                    $item['no_base_source'] = AZLib::remove_4_js(str_replace(array("<br>", "<br />"), '', $item['brief']));

                    $item['description'] = AZLib::plainText(AZLib::parseBBCode(html_entity_decode($item['description'], ENT_QUOTES, "UTF-8")));
                    $item['description'] = preg_replace("/\\[([\s]*[0-9]{1,2}[\s]*)\]/eis", " ", $item['description']);
                    $item['description'] = str_replace(array("'", "\""), array("", " "), $item['description']);
                    $item['description'] = AZLib::word_limit($item['description'], 250, '');

                    /* if($item['sapo']!=''){
                      $item['brief'] = $item['sapo'];
                      $item['brief'] = AZLib::subString(AZLib::filter_title($item['brief']),0,255,true);
                      $item['brief'] = AZLib::word_limit($item['brief'],30,'');
                      }
                      else{
                      $item['brief'] = String::display_sort_title($item['description'],30);
                      } */

                    $item['brief'] = '';

                    $item['parent_name'] = '';

                    if (isset(CGlobal::$allCategories[$item['category_id']]) && CGlobal::$allCategories[$item['category_id']]['parent_id']) {
                        $parent_id = CGlobal::$allCategories[$item['category_id']]['parent_id'];

                        if (isset(CGlobal::$allCategories[$parent_id])) {
                            $item['parent_name'] = CGlobal::$allCategories[$parent_id]['name'] . ' - ';
                        }
                    }

                    if (isset(CGlobal::$allCategories[$item['category_id']]['name'])) {
                        $item['category_name'] = $item['parent_name'] . CGlobal::$allCategories[$item['category_id']]['name'];
                    } else {
                        $item['category'] = '';
                        $item['category_name'] = '';
                    }
                    $item['safe_title'] = AZLib::safe_title($item['parent_name'] . $item['category_name']);
                    $item['category_href'] = WEB_DIR . AZRewrite::formatUrl('?page=list_detail&category_id=' . $item['category_id'] . '&ebname=' . $item['safe_title']);

                    $item['name'] = AZLib::subString(AZLib::filter_title($item['name']), 0, 115, true);
                    $item['name'] = AZLib::word_limit($item['name'], 12, '');

                    $item['user_name'] = $item['user_name'];
                    $item['profile_url'] = WEB_DIR . $item['user_name'];

                    $item['city'] = CGlobal::$provinces[$item['province_id']]['name'];


                    if ($item['img_url']) {
                        $item['img_url'] = AZLib::getImageThumb($item['img_url'], 110, 0, 1, $item['img_server']);
                    } else {
                        $item['img_url'] = 'style/images/no-images-69x53.jpg';
                    }

                    if (isset($_GET['ebname'])) {
                        $item['up_url'] = Url::build_current(array('action' => 'up', 'id' => $item['id'], 'category_id' => CGlobal::$curCategory, 'type' => Url::get('type'), 'ebname' => $_GET['ebname']));

                        $item['down_url'] = Url::build_current(array('action' => 'down', 'id' => $item['id'], 'category_id' => CGlobal::$curCategory, 'type' => Url::get('type'), 'ebname' => $_GET['ebname']));
                    } else {

                        $item['up_url'] = Url::build_current(array('action' => 'up', 'id' => $item['id'], 'category_id' => CGlobal::$curCategory, 'type' => Url::get('type')));

                        $item['down_url'] = Url::build_current(array('action' => 'down', 'id' => $item['id'], 'category_id' => CGlobal::$curCategory, 'type' => Url::get('type')));
                    }
                    $item['in_wish_list'] = false;

                    if (User::is_login()) {
                        if (in_array($item['id'], $w_items)) {
                            $item['in_wish_list'] = true;
                        } else {
                            $item['in_wish_list'] = false;
                        }
                    } else {
                        if (isset($_COOKIE['wish_list_item_ids'])) {
                            $arr = explode(',', $_COOKIE['wish_list_item_ids']);
                            foreach ($arr as $k => $v) {
                                if ($v == $item['id']) {
                                    $item['in_wish_list'] = true;
                                }
                            }
                        }
                    }

                    if (CGlobal::$user_profile['id'] == User::id())
                        $tooltip.= ' - <strong>ID tin: ' . $item['id'] . '</strong>';

                    $item['invalid'] = '';
                    if ($item['status'] == 2) {
                        $tooltip.= '<div style=\\\'color:red\\\'>(Đang kiểm duyệt)</div>';
                        $item['invalid'] = '<font color="red">(Đang kiểm duyệt)</font>';
                    } elseif ($item['status'] == 3) {
                        $tooltip.= '<div style=\\\'color:red\\\'>(Tin theo dõi lừa đảo)</div>';
                        $item['invalid'] = '<font color="red">(Theo dõi lừa đảo)</font>';
                    } elseif ($item['status'] == 0) {
                        $tooltip.= '<div style=\\\'color:red\\\'>(Đang ẩn)</div>';
                        $item['invalid'] = '<font color="red">(Đang ẩn)</font>';
                    } elseif ($item['status'] == 5) {
                        $tooltip.= '<div style=\\\'color:red\\\'>(Đang kiểm duyệt chờ chứng thực)</div>';
                        $item['invalid'] = '<font color="red">(KD chờ chứng thực)</font>';
                    } elseif ($item['status'] == 4) {
                        $tooltip.= '<div style=\\\'color:red\\\'>(Tin trùng)</div>';
                        $item['invalid'] = '<font color="red">(Tin trùng)</font>';
                    } elseif ($item['state'] == 1) {
                        $tooltip.= '<div style=\\\'color:red\\\'>(Đang khóa)</div>';
                        $item['invalid'] = '<font color="red">(Đang khóa)</font>';
                    }

                    $item['tooltip'] = $tooltip;
                    $item['lids'] = '';
                    $item_ids.= ( $item_ids != '' ? ',' : '') . $item['id'];
                    $items[$item['id']] = $item;
                }
            }

            if ($item_ids) {
                $item_labels = array(); //Label của tất cả sp đang đc hiển thị
                $re = DB::query("SELECT id, label_id, item_id FROM label_item WHERE item_id IN($item_ids)");
                if ($re) {
                    while ($l_item = mysql_fetch_assoc($re)) {
                        if (isset($items[$l_item['item_id']])) {
                            $items[$l_item['item_id']]['lids'].= ( $items[$l_item['item_id']]['lids'] != '' ? ',' : '') . $l_item['label_id'];
                        }
                    }
                }
            }
        }
        $display->add('loading_ajax', true);
        $display->add('is_admin', (int) User::have_permit(ADMIN_ITEM));
        $display->add('cur_id', (int) User::id());
        $display->add('total_sp', (int) $total_item);
        $display->add('items', $items);

        $display->add('paging', $pagging);
        $display->add('item_per_page', $item_per_page);

        $display->add('page_num', $page_shop_item);

        $display->add('shop_user_id', CGlobal::$user_profile['id']);
        $display->add('shop_user_name', CGlobal::$user_profile['user_name']);

        $display->output(($list_type != 1 ? 'ShopItem' : 'ShopItemListDetail'), false, 'Shop');
    }

}

//class
?>